package com.event.management.frontend.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.event.management.frontend.common.Result;
import com.event.management.frontend.dto.OrderCreateDTO;
import com.event.management.frontend.dto.OrderDTO;
import com.event.management.frontend.dto.OrderDetailDTO;
import com.event.management.frontend.dto.OrderStatusDTO;
import com.event.management.frontend.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单控制器
 */
@Api(tags = "用户报名购票接口")
@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/front")
public class OrderController {

    private final OrderService orderService;

    /**
     * 创建订单 - 需要登录
     */
    @ApiOperation("创建订单")
    @PostMapping("/orders/create")
    @SaCheckLogin
    public Result<Long> createOrder(@RequestBody @Validated OrderCreateDTO orderCreateDTO) {
        // 从当前用户上下文获取userId
        Long userId = Long.valueOf(StpUtil.getLoginIdAsString());

        // 创建订单（已完成自动支付）
        Long orderId = orderService.createOrder(userId, orderCreateDTO);

        log.info("用户创建订单: userId={}, orderId={}, eventId={}", userId, orderId, orderCreateDTO.getEventId());

        return Result.ok(orderId, "购票成功！您可以在我的订单中查看电子票");
    }

    /**
     * 支付订单 - 需要登录
     */
    @ApiOperation("支付订单")
    @PostMapping("/orders/pay/{id}")
    @SaCheckLogin
    public Result<OrderStatusDTO> payOrder(@ApiParam("订单ID") @PathVariable Long id) {
        // 从当前用户上下文获取userId
        Long userId = Long.valueOf(StpUtil.getLoginIdAsString());

        // 支付订单
        boolean success = orderService.payOrder(userId, id);

        // 获取订单状态（包含电子票信息）
        OrderStatusDTO statusDTO = orderService.getOrderStatus(id);

        log.info("用户支付订单: userId={}, orderId={}, success={}", userId, id, success);

        return Result.ok(statusDTO);
    }

    /**
     * 查询订单状态 - 无需登录，通过订单ID查询
     */
    @ApiOperation("查询订单状态")
    @GetMapping("/orders/status/{id}")
    public Result<OrderStatusDTO> getOrderStatus(@ApiParam("订单ID") @PathVariable Long id) {
        OrderStatusDTO statusDTO = orderService.getOrderStatus(id);
        return Result.ok(statusDTO);
    }

    /**
     * 我的订单列表 - 需要登录
     */
    @ApiOperation("我的订单列表")
    @GetMapping("/orders")
    @SaCheckLogin
    public Result<Result.Page<OrderDTO>> getMyOrders(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int page,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") int size,
            @ApiParam("搜索关键词") @RequestParam(required = false) String keyword,
            @ApiParam("订单状态") @RequestParam(required = false) String status) {
        
        log.info("查询订单列表: page={}, size={}, keyword={}, status={}", page, size, keyword, status);
        
        // 从当前用户上下文获取userId
        Long userId = Long.valueOf(StpUtil.getLoginIdAsString());
        
        // 处理查询参数
        String searchKeyword = (keyword == null || keyword.trim().isEmpty()) ? null : keyword.trim();
        String searchStatus = (status == null || status.trim().isEmpty()) ? null : status.trim();

        // 查询订单列表
        List<OrderDTO> orders = orderService.getFilteredOrders(userId, page, size, searchKeyword, searchStatus);

        // 查询总数
        long total = orderService.countFilteredOrders(userId, searchKeyword, searchStatus);

        // 封装分页结果
        Result.Page<OrderDTO> pageResult = new Result.Page<>();
        pageResult.setRecords(orders);
        pageResult.setTotal(total);
        pageResult.setCurrent(page);
        pageResult.setSize(size);

        return Result.ok(pageResult);
    }

    /**
     * 订单详情 - 需要登录
     */
    @ApiOperation("订单详情")
    @GetMapping("/orders/{id}")
    @SaCheckLogin
    @Caching(evict = {
        @CacheEvict(value = "orderCache", key = "'orderDetail_' + #userId + '_' + #id", allEntries = true),
        @CacheEvict(value = "orderCache", key = "'orderStatus_' + #id", allEntries = true)
    })
    public Result<OrderDetailDTO> getOrderDetail(@ApiParam("订单ID") @PathVariable Long id) {
        // 从当前用户上下文获取userId
        Long userId = Long.valueOf(StpUtil.getLoginIdAsString());

        // 查询订单详情
        OrderDetailDTO detailDTO = orderService.getOrderDetail(userId, id);
        
        // 添加日志记录，确认联系人信息是否包含在响应中
        log.info("订单详情响应 - 联系人信息: orderId={}, contactEmail={}, birthDate={}, country={}", 
            id, detailDTO.getContactEmail(), detailDTO.getBirthDate(), detailDTO.getCountry());

        return Result.ok(detailDTO);
    }

    /**
     * 取消订单（仅限未支付状态）- 需要登录
     */
    @ApiOperation("取消订单")
    @PostMapping("/orders/{id}/cancel")
    @SaCheckLogin
    public Result<Boolean> cancelOrder(@ApiParam("订单ID") @PathVariable Long id) {
        // 从当前用户上下文获取userId
        Long userId = Long.valueOf(StpUtil.getLoginIdAsString());

        // 取消订单
        boolean success = orderService.cancelOrder(userId, id);

        log.info("用户取消订单: userId={}, orderId={}, success={}", userId, id, success);

        return Result.ok(success);
    }
} 